package com.lagou.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lagou.common.feign.GoodsFeign;
import com.lagou.common.pojo.Goods;
import com.lagou.common.pojo.OrderQuery;
import com.lagou.common.pojo.PayOrder;
import com.lagou.order.service.OrderService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private GoodsFeign goodsFeign;

    @GetMapping("/query/{id}")
    public PayOrder queryOrderById(@PathVariable Integer id){
        return orderService.queryOrderById(id);
    }

    @PostMapping("query/{current}/{size}")
    public Map queryByPage(@PathVariable Integer current, @PathVariable Integer size, @RequestBody(required = false) OrderQuery orderQuery){

        Page<PayOrder> page = new Page<>(current,size);
        //构建条件
        QueryWrapper<PayOrder> queryWrapper = new QueryWrapper<>();

        if (orderQuery != null){
            String beginTime = orderQuery.getBeginTime();
            String endTime = orderQuery.getEndTime();
            String status = orderQuery.getStatus();

            //判断条件值是否为空,如果不为空,拼接条件
            if (!StringUtils.isEmpty(beginTime)) {
                queryWrapper.le("created_time", beginTime);
            }
            if (!StringUtils.isEmpty(endTime)) {
                queryWrapper.gt("created_time", endTime);
            }
            if (!StringUtils.isEmpty(status)){
                queryWrapper.eq("status",status);
            }

        }

        Page<PayOrder> goodsPage = orderService.queryByPage(page, queryWrapper);

        long total = goodsPage.getTotal();
        List<PayOrder> records = goodsPage.getRecords();
        HashMap<Object, Object> map = new HashMap<>();
        map.put("list", records);
        map.put("total", total);
        return map;

    }


    @GetMapping("/getGoodsByOrderId/{id}")
    public Goods getGoodsByOrderId(@PathVariable Integer id) throws InterruptedException {
        PayOrder order = orderService.queryOrderById(id);
        Integer goodsId = order.getGoodsId();
        return goodsFeign.queryGoodsById(goodsId);
    }

}
